﻿<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>编辑页面</title>
    <script type="text/javascript" src="/static/js/jquery-3.3.1.min.js"></script>
    <link rel="stylesheet" href="/static/css/global.css">
    <link href="/static/css/bootstrap.css" rel="stylesheet">
    <link href="/static/css/styles.css" rel="stylesheet">
    <script type="text/javascript" src="/static/jquery-ui-1.12.1/jquery-ui.js"></script>
    <script type="text/javascript" src="/static/js/pdemo10.js"></script>
    <link rel="stylesheet" type="text/css" href="/static/jquery-ui-1.12.1/jquery-ui.css">
    <link rel="stylesheet" type="text/css" href="/static/css/style.css">
    <script src="/static/js/bootstrap.js"></script>
    <script type="text/javascript" src="/static/js/jquery.form.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.js"></script>
    <script type="text/javascript">
        function sub() {
            // jquery 表单提交   
            $("#formId").ajaxSubmit(function (message) {
                // 对于表单提交成功后处理，message为返回内容   
            });
            // 必须返回false，否则表单会自己再做一次提交操作，并且页面跳转   
            return false;
        }
    </script>
</head>

<body>
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#"><span>Lemon</span>Pai</a>
                <ul class="user-menu">
                    <li class="dropdown pull-right">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span
                                class="glyphicon glyphicon-user"></span> User <span class="caret"></span></a>
                        <ul class="dropdown-menu" role="menu">
                            <li><a href="#"><span class="glyphicon glyphicon-user"></span> Profile</a></li>
                            <li><a href="#"><span class="glyphicon glyphicon-cog"></span> Settings</a></li>
                            <li><a href="#"><span class="glyphicon glyphicon-log-out"></span> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
    <div id="sidebar-collapse" class="col-sm-1 col-md-1 col-lg-1 sidebar">
        <form>
            <div class="form-group">
                <label>
                    文章标题：
                    <input type="text" class="form-control" id="input_title">
                </label>
            </div>
        </form>
        <ul class="nav menu text-center" id="menu">
            <li><a href="/home"><span class="hidden-xs glyphicon glyphicon-home"></span>
                    <div class="pull-right visible-lg text-center">返回主页</div>
                </a></li>
            <li><a href="javascript:" id="textld"><span class="hidden-xs glyphicon glyphicon-dashboard"></span>
                    <div class="pull-right visible-lg text-center">插入文本</div>
                </a></li>
            <li><a href="javascript:" id="imgld"><span class="hidden-xs glyphicon glyphicon-th"></span>
                    <div class="pull-right visible-lg text-center">插入图片</div>
                </a></li>
            <li><a href="javascript:" id="videold"><span class="hidden-xs glyphicon glyphicon-stats"></span>
                    <div class="pull-right visible-lg text-center">插入视频</div>
                </a></li>
            <li><a href="javascript:" id="button_pptCreation"><span class="hidden-xs glyphicon glyphicon-pencil"></span>
                    <div class="pull-right visible-lg text-center">插入新页</div>
                </a></li>
            <li><a href="javascript:" id="button_pptRemove"><span class="hidden-xs glyphicon glyphicon-pencil"></span>
                    <div class="pull-right visible-lg text-center">删除本页</div>
                </a></li>
            <li><a href="javascript:" id="play_start"><span class="hidden-xs glyphicon glyphicon-pencil"></span>
                    <div class="pull-right visible-lg text-center">开始放映</div>
                </a></li>
            <li><a href="javascript:" id="save"><span class="hidden-xs glyphicon glyphicon-pencil"></span>
                    <div class="pull-right visible-lg text-center">&nbsp;&nbsp;保存&nbsp;&nbsp;&nbsp;&nbsp;</div>
                </a></li>
            <li style="display:none;"><a href="javascript:" id="get"><span
                        class="hidden-xs glyphicon glyphicon-pencil"></span>
                    <div class="pull-right visible-lg text-center">&nbsp;&nbsp;&nbsp;Get！&nbsp;&nbsp;</div>
                </a></li>
            <li style="display:none;"><a href="javascript:" id="test1"><span
                        class="hidden-xs glyphicon glyphicon-pencil"></span>
                    <div class="pull-right visible-lg text-center">&nbsp;&nbsp;&nbsp;test1&nbsp;&nbsp;&nbsp;</div>
                </a></li>
            <li role="presentation" class="divider"></li>
        </ul>
    </div>
    <form style="display:none;" id="formId" method="post" enctype="multipart/form-data" onsubmit="return sub();">
        <input id="inimgld" type="file" name="image">
        <button id="imgsubmit" class="submit" type="submit">提交</button>
    </form>
    <script type="text/javascript">

        const BTN1 = document.getElementById('inimgld');
        const BTN2 = document.getElementById('imgld');
        const BTN3 = document.getElementById('imgsubmit');

        //******************第一部分 图片功能******************\\
        //给按钮2添加点击事件,此按钮用于添加图片功能
        BTN2.addEventListener('click', () => {
            //按钮2点击后触发按钮1的onclick，按钮1隐藏显示，作用是调用本地文件
            BTN1.click();
        });

        var x = new FileReader;
        document.forms[1].elements[0].onchange = function () {
            x.readAsDataURL(this.files[0]);
        }

        x.onloadend = function () {
            //BTN3.click();选择图片时的“确定”按钮
            if (current_id == 0) {
                $("#inimgld").val('');
            }
            document.images[(current_id - 1) * 6 + imgCount[current_id - 1]].src = this.result;
            var img_remove = document.getElementsByClassName("img-remove")[(current_id - 1) * 12 + imgCount[current_id - 1]];
            img_remove.style.display = "inline";
            var oDiv0 = document.getElementsByClassName('box')[(current_id - 1) * 6 + imgCount[current_id - 1]];
            oDiv0.style.display = "inline";
            oDiv0.style.width = '200px';
            oDiv0.style.height = '120px';
            imgCount[current_id - 1]++;
            $("#inimgld").val('');
        }

        //******************第二部分 视频功能******************\\
        //101-189为视频功能，功能未完善，目前未启用
        $("#videold").click(function () {
            var cha = document.getElementsByClassName('section')[(current_id - 1) * 6 + videoBoxCount[current_id - 1]];
            cha.style.display = "block";
            cha.getElementsByClassName('img-remove')[0].style.display = "block";

            videoBoxCount[current_id - 1]++;
        });
        function onUpload2_0(file) {
            var blob = new Blob([file]),
                url = URL.createObjectURL(blob);
            if (/video/g.test(file.type)) {
                var video = $('<video controls src="' + url + '">');
                var current_video_div = "#out" + current_id;
                $('#preview1', $(current_video_div)).html('').append(video);
                $('#upload1', $(current_video_div)).remove();
                video[(current_id - 1) * 6].onload = function (e) {
                    URL.revokeObjectURL(this.src);
                }
            }
        }
        function onUpload2_1(file) {
            var blob = new Blob([file]),
                url = URL.createObjectURL(blob);
            if (/video/g.test(file.type)) {
                var video = $('<video controls src="' + url + '">');
                var current_video_div = "#out" + current_id;
                $('#preview2', $(current_video_div)).html('').append(video);
                $('#upload2', $(current_video_div)).remove();
                video[1 + (current_id - 1) * 6].onload = function (e) {
                    URL.revokeObjectURL(this.src);
                }
            }
        }
        function onUpload2_2(file) {
            var blob = new Blob([file]),
                url = URL.createObjectURL(blob);
            if (/video/g.test(file.type)) {
                var video = $('<video controls src="' + url + '">');
                var current_video_div = "#out" + current_id;
                $('#preview3', $(current_video_div)).html('').append(video);
                $('#upload3', $(current_video_div)).remove();
                video[2 + (current_id - 1) * 6].onload = function (e) {
                    URL.revokeObjectURL(this.src);
                }
            }
        }
        function onUpload2_3(file) {
            var blob = new Blob([file]),
                url = URL.createObjectURL(blob);
            if (/video/g.test(file.type)) {
                var video = $('<video controls src="' + url + '">');
                var current_video_div = "#out" + current_id;
                $('#preview4', $(current_video_div)).html('').append(video);
                $('#upload4', $(current_video_div)).remove();
                video[3 + (current_id - 1) * 6].onload = function (e) {
                    URL.revokeObjectURL(this.src);
                }
            }
        }
        function onUpload2_4(file) {
            var blob = new Blob([file]),
                url = URL.createObjectURL(blob);
            if (/video/g.test(file.type)) {
                var video = $('<video controls src="' + url + '">');
                var current_video_div = "#out" + current_id;
                $('#preview5', $(current_video_div)).html('').append(video);
                $('#upload5', $(current_video_div)).remove();
                video[4 + (current_id - 1) * 6].onload = function (e) {
                    URL.revokeObjectURL(this.src);
                }
            }
        }
        function onUpload2_5(file) {
            var blob = new Blob([file]),
                url = URL.createObjectURL(blob);
            if (/video/g.test(file.type)) {
                var video = $('<video controls src="' + url + '">');
                var current_video_div = "#out" + current_id;
                $('#preview6', $(current_video_div)).html('').append(video);
                $('#upload6', $(current_video_div)).remove();
                video[5 + (current_id - 1) * 6].onload = function (e) {
                    URL.revokeObjectURL(this.src);
                }
            }
        }


        //******************额外部分 保存登录用户信息功能******************\\
        // const URL = 'http://172.20.34.120:5000';
        const URL = '';
        $.ajaxSetup({ async: false });
        var username;
        function query_username() {
            $.ajax({
                type: 'post',
                url: URL + '/json/username',
                data: username,
                contentType: false,
                processData: false,
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (data) {
                    console.log(data);
                },
            });
        };
        query_username();
        var articleList;
        $("#test1").on("click", function () {
            let formdata = new FormData();

            let title = prompt("请输入文章标题");
            if (title.length != 0) {
                formdata.append("title", title);
            }
            $.ajax({
                url: URL + '/json/create_article',
                data: formdata,
                type: "POST",
                processData: false,//用于对data参数进行序列化处理 这里必须false
                contentType: false, //必须
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (data) {//data就是从服务器上接收的数据，可以是字符串，也可以是数组或字符串组
                    articleId = data["id"];
                }
            });
        });

        //******************第三部分 文本功能******************\\
        var mark = 1, tp = 2;
        var t = 2;
        var T, R, temp;
        $("#textld").on("click ", function () {
            var current_page = "out" + current_id;
            var html = '<div id="box" class="mybox" style="background:#F0FFF0;width:280px; height:150px;left:200px;top:100px;border:1.8px dashed #C0C0C0;padding:8px;min-width:200px;min-height:100px"><a href="javascript:" class="text-remove">x</a><div class="innerbox" contenteditable="true" style="width:100%; height:100%;"></div></div>';
            var odiv = document.getElementById(current_page);
            $(odiv).append(html);
            $(".mybox").click(function () {
                this.style.zIndex = t;
                t++;
            });
            //为新建文本框设置拖拽、放缩功能
            $(".mybox").draggable({ containment: "parent" });
            $(".mybox").draggable({ cancel: "div.innerbox" });
            $(".mybox").resizable({});
            //为新建文本框各要素重命名
            //规范化id：box_ppt页数(从1开始)_当前ppt页文本数(从0开始)
            T = "box_" + current_id + "_" + textCount[current_id - 1];
            document.getElementById("box").id = T;
            //规范化id：textarea_ppt页数(从1开始)_当前ppt页文本数(从0开始)
            T = "textarea_" + current_id + "_" + textCount[current_id - 1];
            //配置红叉的删除功能
            $(".text-remove").click(function () {
                $(this.parentNode).remove();
            });
            document.querySelector("input").addEventListener("input", function () {
                //让 scrollWidth 获取最小值，达到回缩的效果
                this.style.width = "0px";
                this.style.width = this.scrollWidth + "px";
            });
            textCount[current_id - 1]++;
        });

        //******************第四部分 保存功能******************\\
        $("#save").on("click", function () {
            var formdata = new FormData();
            var newdata = new FormData();
            let new_art_title = $('#input_title').val();
            if (new_art_title.length === 0 || new_art_title.length > 30) {
                new_art_title = art_title;
            }
            console.log('新的标题： ' + art_title);
            newdata.append("title", new_art_title);
            newdata.append("edit", true);
            // 修改模式
            newdata.append('id_debug', articleId);
            newdata.append('title_debug', art_title);
            console.log(art_title);
            var Img = new FormData();
            var _imgsize = new Array();
            var _textsize = new Array();
            var cnt = 0;
            for (var k = 0; k < pptCount; ++k) {
                cnt = 0;
                var tmp0 = document.getElementsByClassName("outbox")[k];
                for (var kk = 0; kk < 6; ++kk) {
                    var tmpimg = tmp0.getElementsByClassName("imgi")[kk];
                    if (typeof (tmpimg) == "undefined") {
                        continue;
                    }
                    if (tmpimg.src.length > 20) {
                        var tmp = tmp0.getElementsByClassName('box draggable box0 ui-draggable ui-draggable-handle')[kk];
                        _imgsize[k] = ++cnt;
                        var t_height = $(tmp).css('height');
                        var t_width = $(tmp).css('width');
                        var t_left = $(tmp).css('left');
                        var t_top = $(tmp).css('top');
                        var t_zindex = $(tmp).css('z-index');
                        formdata.append("width_" + k + "_" + kk, t_width);
                        formdata.append("height_" + k + "_" + kk, t_height);
                        formdata.append("left_" + k + "_" + kk, t_left);
                        formdata.append("top_" + k + "_" + kk, t_top);
                        formdata.append("zindex_" + k + "_" + kk, t_zindex);
                    }
                }
            }
            for (var k = 0; k < pptCount; ++k) {
                cnt = 0;
                var tmp0 = document.getElementsByClassName("outbox")[k];
                for (var kk = 0; kk < textCount[k]; ++kk) {
                    var tmpbox = tmp0.getElementsByClassName("innerbox")[kk];
                    if (typeof (tmpbox) == "undefined") {
                        continue;
                    }
                    if (tmpbox.innerText.length > 0) {
                        var tmp = tmp0.getElementsByClassName('mybox')[kk];
                        _textsize[k] = ++cnt;
                        var t_height = $(tmp).css('height');
                        var t_width = $(tmp).css('width');
                        var t_left = $(tmp).css('left');
                        var t_top = $(tmp).css('top');
                        var t_zindex = $(tmp).css('z-index');
                        formdata.append("twidth_" + k + "_" + kk, t_width);
                        formdata.append("theight_" + k + "_" + kk, t_height);
                        formdata.append("tleft_" + k + "_" + kk, t_left);
                        formdata.append("ttop_" + k + "_" + kk, t_top);
                        formdata.append("tzindex_" + k + "_" + kk, t_zindex);
                        formdata.append("tcontent_" + k + "_" + kk, tmpbox.innerText);
                    }
                }
            }
            formdata.append("pageindex", pptCount);
            for (var i = 0; i < pptCount; i++) {
                formdata.append("imgsize" + i, _imgsize[i]);
                formdata.append("textsize" + i, _textsize[i]);
            }
            var objData = {};
            for (var entry of formdata.entries()) {
                objData[entry[0]] = entry[1];
            }
            newdata.append("content", JSON.stringify(objData));
            $.ajax({
                url: URL + '/edit',
                data: newdata,
                type: "POST",
                dataType: false,
                //上传文件无需缓存
                cache: false,
                //用于对data参数进行序列化处理 这里必须false
                processData: false,
                //必须
                contentType: false,
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (data) {
                    //data就是从服务器上接收的数据，可以是字符串，也可以是数组或字符串组
                }
            });
            $.ajaxSetup({ async: false });
            for (var k = 0; k < pptCount; ++k) {
                var tmp0 = document.getElementsByClassName("outbox")[k];
                for (var kk = 0; kk < 6; ++kk) {
                    var tmpimg = tmp0.getElementsByClassName("imgi")[kk];
                    if (tmpimg.src == "") {
                        _imgsize[k] = kk;
                        break;
                    }
                    var t_src = tmpimg.src;
                    var temp = t_src.split(",");
                    var _Img = new FormData();
                    _Img.append("filename", "img" + articleId + "_" + k + "_" + kk + ".jpg");
                    _Img.append("content", temp[1]);
                    _Img.append("id_debug", articleId)
                    $.ajax({
                        url: URL + '/json/upload_base64',
                        data: _Img,
                        type: "POST",
                        dataType: false,
                        //上传文件无需缓存
                        cache: false,
                        //用于对data参数进行序列化处理 这里必须false
                        processData: false,
                        //必须
                        contentType: false,
                        xhrFields: { withCredentials: true },
                        crossDomain: true,
                        success: function (data) {
                            //data就是从服务器上接收的数据，可以是字符串，也可以是数组或字符串组
                        }
                    });
                }
            }
            location.pathname = '/home'
        });
        var anotherdata;
        var dic;
        var _pageindex = 0;
        $.ajaxSetup({ async: false });
        $("#get").on("click", function () {
            current_id = 0;
            var cnt1 = 0;
            $.ajax({
                url: URL + '/json/article_query?id=' + articleId + '&title=' + art_title,
                data: '',
                type: "POST",
                //用于对data参数进行序列化处理 这里必须false
                processData: false,
                //必须
                contentType: false,
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (data) {
                    //data就是从服务器上接收的数据，可以是字符串，也可以是数组或字符串组
                    dic = JSON.parse(data["content"]);
                    _pageindex = parseInt(dic["pageindex"].trim());
                }
            });
            var fformdata = new FormData();
            var imgfielname = new Array();
            var imgcnt = 0;
            for (var i = 0; i < _pageindex; ++i) {
                var str = "imgsize" + i;
                for (var j = 0; j < parseInt(dic[str].trim()); ++j) {
                    var ttmp = "img" + articleId + "_" + i + "_" + j + ".jpg";
                    imgfielname[imgcnt++] = ttmp;
                }
            }
            var imgdic = {};
            fformdata.append('filenames', JSON.stringify(imgfielname));
            $.ajax({
                url: URL + '/json/get_base64_multiple',
                data: fformdata,
                type: "POST",
                //用于对data参数进行序列化处理 这里必须false
                processData: false,
                //必须
                contentType: false,
                xhrFields: { withCredentials: true },
                crossDomain: true,
                success: function (data) {
                    imgdic = data;
                }
            });
            console.log(dic);
            var textcnt = 0;
            for (var i = 0; i < _pageindex; ++i) {
                $("#button_pptCreation").click();
                current_id = i + 1;
                var tnum = "textsize" + i;
                var str = "imgsize" + i;
                //加页码
                for (var j = 0; j < parseInt(dic[str].trim()); ++j) {
                    var ttmp = "data:image/jpeg;base64," + imgdic["img" + articleId + "_" + i + "_" + j + ".jpg"];
                    if (current_id == 0) {
                        $("#inimgld").val('');
                    }
                    document.images[(current_id - 1) * 6 + imgCount[current_id - 1]].src = ttmp;
                    var img_remove = document.getElementsByClassName("img-remove")[(current_id - 1) * 12 + imgCount[current_id - 1]];
                    img_remove.style.display = "inline";
                    var oDiv0 = document.getElementsByClassName('box')[(current_id - 1) * 6 + imgCount[current_id - 1]];
                    oDiv0.style.display = "inline";
                    oDiv0.style.width = dic["width" + "_" + i + "_" + j].trim();
                    oDiv0.style.height = dic["height" + "_" + i + "_" + j].trim();
                    oDiv0.style.top = dic["top" + "_" + i + "_" + j].trim();
                    oDiv0.style.left = dic["left" + "_" + i + "_" + j].trim();
                    $(oDiv0).css('z-index', dic["zindex" + "_" + i + "_" + j].trim());
                    imgCount[current_id - 1]++;
                    $("#inimgld").val('');
                    t += 30;
                    $(".box0").click(function () {
                        this.style.zIndex = t;
                        t++;
                    });
                }
                for (var j = 0; j < parseInt(dic[tnum]); ++j) {

                    $('#textld').click();
                    var Box0 = document.getElementsByClassName('mybox')[textcnt];
                    var Text0 = document.getElementsByClassName('innerbox')[textcnt];
                    textcnt++;
                    Box0.style.width = dic["twidth" + "_" + i + "_" + j].trim();
                    Box0.style.height = dic["theight" + "_" + i + "_" + j].trim();
                    Box0.style.top = dic["ttop" + "_" + i + "_" + j].trim();
                    Box0.style.left = dic["tleft" + "_" + i + "_" + j].trim();
                    $(Box0).css('z-index', dic["tzindex" + "_" + i + "_" + j].trim());
                    Text0.innerText = dic["tcontent" + "_" + i + "_" + j];
                    t += 10;
                    $(".box0").click(function () {
                        this.style.zIndex = t;
                        t++;
                    });
                }
                $(".outbox")[0].style.display = "inline";
            }
            for (var ii = 1; ii < _pageindex; ii++) {
                $(".outbox")[ii].style.display = "none";
            }

            $('#input_title').val(art_title);

            // 为了解决玄学问题的刷新操作
            // if ($.cookie('load_once') !== 'yes') {
            // 	$.cookie('load_once', 'yes');
            // 	console.log('准备刷新！');
            // 	setTimeout(function () {
            // 		location.reload();
            // 	}, 2000);
            // }
            // else {
            // 	$.cookie('load_once', null);
            // }
        });


        function dataURLtoFile(dataurl, filename = 'file') {
            let arr = dataurl.split(',')
            let mime = arr[0].match(/:(.*?);/)[1]
            let suffix = mime.split('/')[1]
            let bstr = atob(arr[1])
            let n = bstr.length
            let u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], `${filename}.${suffix}`, {
                type: mime
            })
        }

        $("#button_pptRemove").on("click", function () {
            var pptId = 'ppt' + current_id;
            var current_HTML = document.getElementById(pptId).childNodes.item(0).childNodes.item(1).innerHTML;
            //设置menu栏的页数符合逻辑
            var aPos = current_HTML.indexOf('第');
            var bPos = current_HTML.indexOf('页');
            var r = parseInt(current_HTML.substr(aPos + 1, bPos - aPos - 1));
            //设置当前ppt页不存在
            is_exist[current_id - 1] = false;
            $("#out" + current_id).remove();
            $("#ppt" + current_id).remove();

            for (var i = current_id + 1; i <= pptCount; i++) {
                //设置menu子项的id
                var pptId = 'ppt' + i;
                var new_pptId = 'ppt' + (i - 1);
                //设置ppt页的id
                var outId = 'out' + i;
                var new_outId = 'out' + (i - 1);
                //获取相关要素
                var current_div = document.getElementById(pptId).childNodes.item(0).childNodes.item(1);
                //修改页数显示信息
                current_div.innerHTML = "第" + (r++) + "页";
                var current_div = document.getElementById(pptId);
                var current_ppt = document.getElementById(outId);
                //设置新id
                current_div.id = new_pptId;
                current_ppt.id = new_outId;
                //将各个数组内容前移
                imgCount[i - 2] = imgCount[i - 1];
                textCount[i - 2] = textCount[i - 1];
                videoBoxCount[i - 2] = videoBoxCount[i - 1];
                videoCount[i - 2] = videoCount[i - 1];
            }
            //最后再减1
            pptCount--;
        });


        window.onbeforeunload(function () {
            $.cookie('load_once', null);
        });
    </script>
</body>

</html>